package com.aishua.fire.controller.sysmanager;

import java.util.List;
import java.util.Map;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aishua.fire.common.JsonArrayResult;
import com.aishua.fire.common.JsonObjectResult;
import com.aishua.fire.common.ValidateUtil;
import com.aishua.fire.common.anno.ModuleService;
import com.aishua.fire.common.anno.PermMapping;
import com.aishua.fire.common.constant.BigMenuConstants;
import com.aishua.fire.common.constant.ModuleConstants;
import com.aishua.fire.common.exp.ValidateException;
import com.aishua.fire.entity.aateam.AddAccountAteamInfo;
import com.aishua.fire.entity.account.AccountBatchInfo;
import com.aishua.fire.entity.account.AccountSameNameInfo;
import com.aishua.fire.entity.account.AccountSearchInfo;
import com.aishua.fire.mapper.dto.AccteamList;
import com.aishua.fire.entity.account.AddAccountInfo;
import com.aishua.fire.entity.account.HuiFuAccountInfo;
import com.aishua.fire.entity.account.UpdPasswordInfo;
import com.aishua.fire.entity.account.UpdateAccountInfo;
import com.aishua.fire.jpa.entity.Account;
import com.aishua.fire.jpa.entity.Accountteam;
import com.aishua.fire.mapper.dto.AccountList;
import com.aishua.fire.service.AccountAteamService;
import com.aishua.fire.service.AccountService;
import com.aishua.fire.service.AccountteamService;
import com.aishua.fire.service.LoginService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

@Api(value = "系统账户模块",tags = {"系统账户模块接口"})
@RestController
@Slf4j
public class SystemAccountController {

	@Autowired
	private AccountService accountService;
	
	@Autowired
	private AccountteamService accountteamService;
	
	@Autowired
	private AccountAteamService accountAteamService;
	
	@Autowired
	private ValidateUtil validateUtil;
	
	@Autowired
	private LoginService loginService;
	/**
	 * weicancan
	 * 测试报文:
	 * post  http://localhost:8080/account
	 * {
			"userName":"test",
			"userPassword":"test",
			"aliasName":"测试账户",
			"emailAddr":"1234@qq.com",
			"phone":"13999999999"
			
		}
	 * @throws ValidateException 
	 * 
	 */
	@SuppressWarnings("rawtypes")
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="新增_添加系统账户信息")
	@PostMapping(value = {"/account"} )
	public ResponseEntity<JsonObjectResult> add(@RequestBody @Valid AddAccountInfo accountInfo,BindingResult result) throws ValidateException {
		log.info("添加账户日志:{}",accountInfo);
		validateUtil.respErrorMsg(result);//非空验证
		String flag = accountService.save(accountInfo);
		loginService.insertSession(Long.parseLong("-1"));	
		
		JsonObjectResult r = null;
		if(StringUtils.isBlank(flag))
		{
			r = JsonObjectResult.makeSuccessResult(null);
		}
		else
		{
			r = JsonObjectResult.makeErrorResult(flag);
		}
		return ResponseEntity.ok(r);
    }
	

	/**
	 * weicancan
	 * 
	 * 测试报文:
	 * post  http://localhost:8080/accountList
	 * {
		  "ateamId": "2",
		  "loginId": null,
		  "page": 0,
		  "size": 10,
		  "userName": null
		}
	 * 
	 */
	@SuppressWarnings("rawtypes")
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="查询_账户信息列表")
	@GetMapping(value = {"/account"} )
	public ResponseEntity<JsonArrayResult> accountList(@RequestParam(name = "username") String username, @RequestParam(name = "phone") String phone,
			@RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize ) 
	{		
		log.info("查询列表请求参数:{}",username);
		List<AccountList> searchList = accountService.searchList(username, phone, pageNumber, pageSize);
		
		int total = accountService.listTotal(username, phone);
		log.info("查询总条数：{}", total);
		JsonArrayResult r = JsonArrayResult.makeSuccessResult(searchList, total);

		return ResponseEntity.ok(r);
    
	}
	
	/**
	 * weicancan
	 * 测试报文:
	 * put http://localhost:8080/test/account
	 * {
			"loginId":"1",
			"aliasName":"ali",
			"staffId":"123",
			"supplierId":"345",
			"userName":"wwe",
			"userPassword":"qqq"
			
		}
	 * @throws ValidateException 
	 */
	@SuppressWarnings("rawtypes")
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="修改_账户信息")
	@PutMapping(value = {"/account"} )
	public ResponseEntity<JsonObjectResult> update(@RequestBody @Valid UpdateAccountInfo loginAccount,BindingResult result) throws ValidateException {
		log.info("修改账户信息:{}",loginAccount);
		validateUtil.respErrorMsg(result);
		boolean flag = accountService.update(loginAccount);

		JsonObjectResult r = null;
		if(flag)
		{
			r = JsonObjectResult.makeSuccessResult(null);
		}
		else
		{
			r = JsonObjectResult.makeErrorResult("该账户名已经存在,无法继续修改");
		}
		return ResponseEntity.ok(r);
        
    }
	
	
	
	/**
	 * gaoyi     2018-04-12
	 * 测试报文:
	 * get  http://localhost:8080/account
	 * {
			"userName":"test",
			"userPassword":"test",
			"aliasName":"测试账户",
			"supplierId":"000",
			"staffId":"000",
			"emailAddr":"1234@qq.com"
			
		}
	 * 
	 */
	@PermMapping(onlyLogin = true)
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="账户详情页面添加账户组之前,获取账户组名称接口")
	@GetMapping(value = {"/accountDetail/before/{accountId}"} )
	public List<Accountteam> addDetailBefore(@PathVariable("accountId") @ApiParam(name="登录账户id",value="类如:0000",required=true) String accountId) {
		List<Accountteam> accountteams = accountteamService.findFilterIdAndName(Long.parseLong(accountId));
		log.info("账户详情页面添加账组户之前日志:{}",accountteams);
		return accountteams;
    }
	
	/**
	 * gaoyi     2018-04-12
	 * 测试报文:
	 * get  http://localhost:8080/account
	 * {
			"userName":"test",
			"userPassword":"test",
			"aliasName":"测试账户",
			"supplierId":"000",
			"staffId":"000",
			"emailAddr":"1234@qq.com"
			
		}
	 * @throws ValidateException 
	 * 
	 */
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="添加_为账户添加角色信息")
	@PostMapping(value = {"/accountDetail/add"} )
	public void addDetail(@RequestBody @Valid AddAccountAteamInfo addInfo,BindingResult result) throws ValidateException {
		log.info("添加账户-账户组表:{}",addInfo);
		validateUtil.respErrorMsg(result);
		//添加账户-账户组表
		accountAteamService.save(addInfo);
    }
	
	/**
	 * 
	 * 添加账户重复校验
	 * gaoyi     2018-04-10
	 * @return
	 */
	/**
	 * 测试报文:
	 * post http://localhost:8080/account/findLoginIdByUserName
	 *		"admin"
	 * @throws ValidateException 
	 */
	@PermMapping(onlyLogin = true)
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="账户重复性验证接口")
	@PostMapping(value = {"/account/findLoginIdByUserName"} )
	public Integer findLoginIdByUserName(@RequestBody @Valid AccountSameNameInfo sameNameInfo,BindingResult result ) throws ValidateException {
		//去掉json格式的""
		log.info("添加账户日志:{}",sameNameInfo);
		validateUtil.respErrorMsg(result);
		//根据loginId查询userName
		Long loginId = accountService.findLoginIdByUserName(sameNameInfo.getLoginId(),sameNameInfo.getUserName());
		if (loginId!=null) {//重复，用户名不可以注册
			return 1;
		}
		return 2;//不重复，用户名可以注册
    }
	
	/**
	 * gaoyi     2018-04-10
	 * 测试报文:
	 * post http://localhost:8080/accountBatch
	 * {
		  "batchLoginId": [
		    2,3,4
		  ]
		}
	 */
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="删除_账户信息(批量)")
	@PostMapping(value = {"/accountBatch"} )
	public String deleteBatch(@RequestBody @ApiParam(name="批量删除信息",value="类如:",required=true) AccountBatchInfo accountBatchInfo) {
		log.info("批量删除账户信息:{}",accountBatchInfo);
		
		accountService.deleteAccountBatch(accountBatchInfo);
//		init.initUrlMap(false);
        
		return null;
    }
	
	
	/**
	 * gaoyi     2018-04-10
	 * 测试报文:
	 * get  http://localhost:8080/test/account/1
	 * 
	 */
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="查询_账户信息详情")
	@GetMapping(value = {"/account/{loginId}"} )
	public Account get(@PathVariable("loginId") @ApiParam(name="登录账户id",value="类如:0000",required=true) String loginId) {
		log.info("查询账户id:{}",loginId);
		return accountService.findAccountId(loginId);
    }
	
	
	/**
	 * gaoyi     2018-04-10
	 * 测试报文:
	 * post  http://localhost:8080/accountListA
	 * {
		  "ateamId": "2",
		  "loginId": "",
		  "page": 0,
		  "size": 10,
		  "userName": ""
		}
	 * 
	 */
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="查询_角色下账户信息列表")
	@PostMapping(value = {"/accountListA"} )
	public List<AccteamList> getAteamList(@RequestBody AccountSearchInfo accountSearchInfo) {
		log.info("查询账户组id:{}",accountSearchInfo.getAteamId());
		List<AccteamList> accounts = accountService.getAccountListByAteamId(accountSearchInfo.getAteamId(), accountSearchInfo.getLoginId(),accountSearchInfo.getUserName());
		return accounts;
    }
	
	
	/**
	 * gaoyi     2018-04-10
	 * 测试报文:
	 * post  http://localhost:8080/account/softDelete
	 * {
		  "batchLoginId": [
		    "2"
		  ]
		}
	 * 
	 */
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="删除_账户信息（软）")
	@PutMapping(value = {"/account/softDelete"} )
	public void softDelete(@RequestBody AccountBatchInfo AccountBatchInfo) {
		log.info("修改账户信息:{}",AccountBatchInfo);
		accountService.softDelete(AccountBatchInfo);
//		init.initUrlMap(false);
        
    }
	
	/**
	 * gaoyi     2018-04-10
	 * 测试报文:
	 * post  http://localhost:8080/account/modifypwd
	 * {
		  "loginId": "1",
		  "userPassword": "aaa"
	   }
	 * @throws ValidateException 
	 * 
	 */
	@PermMapping(onlyLogin = true)
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="修改_账户登录密码")
	@PostMapping(value = {"/account/modifypwd"} )
	public void modifypwd(@RequestBody @Valid UpdPasswordInfo updPasswordInfo,BindingResult result) throws ValidateException {
		log.info("修改密码:{}",updPasswordInfo);
		validateUtil.respErrorMsg(result);
		//修改密码
		accountService.modifypwd(updPasswordInfo.getUserPassword(),updPasswordInfo.getLoginId());
    }
	
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="添加_账户角色信息")
	@PostMapping(value = {"/accountAteam"} )
	public void add(@RequestBody AddAccountAteamInfo accountInfo) {
		log.info("添加账户关联账户组日志:{}",accountInfo);
		accountAteamService.save(accountInfo);
//		init.initUrlMap(false);
    }
	
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="删除_账户角色信息")
	@DeleteMapping(value = {"/accountAteam/{accountId}/{accountteamId}"} )
	public void delete(@PathVariable @ApiParam(name="登录账户id",value="类如:0000",required=true) String accountId,
			@PathVariable @ApiParam(name="登录账户id",value="类如:0000",required=true) String accountteamId) {
		log.info("删除账户关联账户组id:{},{}",accountId,accountteamId);
		accountAteamService.delete(accountId,accountteamId);
//		init.initUrlMap(false);
		 
    }
	
	@PermMapping(onlyLogin = true)
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="删除账户关联账户组信息接口")
	@PostMapping(value = {"/account/forbid"} )
	public void forbidAccount(@RequestBody UpdateAccountInfo loginAccount) {
		log.info("禁止账户id:{},{}",loginAccount.getLoginId());
		accountService.forbidAccount(loginAccount.getLoginId());
//		init.initUrlMap(false);
		 
    }
	
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="恢复_账户信息")
	@PostMapping(value = {"/account/huifu"} )
	public void huiFuAccount(@RequestBody HuiFuAccountInfo loginAccount) {
		log.info("恢复账户id:{},{}",loginAccount.getLoginId());
		accountService.huiFuAccount(loginAccount.getLoginId());
//		init.initUrlMap(false);
        
    }
	
	
	/**
	 * gaoyi     2018-04-11
	 * 测试报文:
	 * post  http://localhost:8080/account
	 * {
			"userName":"test",
			"userPassword":"test",
			"aliasName":"测试账户",
			"supplierId":"000",
			"staffId":"000",
			"emailAddr":"1234@qq.com"
			
		}
	 * 
	 */
	@PermMapping(onlyLogin = true)
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="添加账户之前,获取供应商和账户组下拉列表接口")
	@GetMapping(value = {"/account/before"} )
	public Map<String, Object> addBefore() {
		Map<String, Object> map = accountService.getAccountteamAndSupplier();
		log.info("添加账户之前日志:{}",map);
		return map;
    }
	
	/**
	 * gaoyi     2018-04-10
	 * 测试报文:
	 * delete http://localhost:8080/test/account/1
	 */
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="删除_账户信息")
	@DeleteMapping(value = {"/account/{loginId}"} )
	public String delete(@PathVariable @ApiParam(name="登录账户id",value="类如:0000",required=true) String loginId) {
		log.info("删除账户id:{}",loginId);
		accountService.deleteAccount(loginId);
//		init.initUrlMap(false);
		
        
		return null;
    }
	
}
